<template>
    <div style="width: 98%;height: 98%;margin-top: 20px;">
		<el-row :gutter="20">
			<el-col :span="24">
				<el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="选择摄像头">
                        <el-select v-model="formInline.videoId" placeholder="摄像头">
                            <el-option v-for="(item,index) in localDevice.videoIn " :key="index" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择麦克风">
                        <el-select v-model="formInline.audioInId" placeholder="麦克风">
                            <el-option v-for="(item,index) in localDevice.audioIn " :key="index" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择听筒">
                        <el-select v-model="formInline.audioOutId" placeholder="听筒">
                            <el-option v-for="(item,index) in localDevice.audioOut " :key="index" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分辨率:Width">
                        <el-input v-model="formInline.width"></el-input>
                    </el-form-item>
                    <el-form-item label="分辨率:Height">
                        <el-input v-model="formInline.height"></el-input>
                    </el-form-item>
                    <el-form-item label="FPS">
                        <el-input v-model="formInline.frameRate"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
                    </el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row>
			<video id="videoElement" ref="videoRef" autoplay controls muted></video>
		</el-row>
	</div>
</template>

<script>
export default {
    name: "WebRtcAPI",
    data() {
        return {
            localDevice: {
                audioIn:[],
                videoIn: [],
                audioOut: []
            },
            formInline: {
                videoId:undefined,
                audioInId:undefined,
                audioOutId:undefined,
                width:1080,
                height:720,
                frameRate:24,
            }
        }
    },
    mounted() {
        this.initInnerLocalDevice()
    },
    methods: {
        handleError(error) {
            console.error('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
        },
        initInnerLocalDevice(){
		    this.localDevice = {
		        audioIn: [],
		        videoIn: [],
		        audioOut: []
		    }
		    let constraints = { video:true, audio: true}
		    if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
		        console.log("浏览器不支持获取媒体设备");
		        return;
		    }
		    navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
                stream.getTracks().forEach(trick => {
                    trick.stop()
                })
                navigator.mediaDevices.enumerateDevices()
                    .then((devices) => {
                        devices.forEach((device) => {
                            let obj = {
                                id: device.deviceId, 
                                kind: device.kind, 
                                label: device.label
                            }
                            if (device.kind === 'audioinput') {
                                if (this.localDevice.audioIn.filter(item => item.id === device.deviceId).length === 0) {
                                    this.localDevice.audioIn.push(obj)
                                }
                            } else if (device.kind === 'audiooutput') {
                                if (this.localDevice.audioOut.filter(item => item.id === device.deviceId).length === 0) {
                                    this.localDevice.audioOut.push(obj)
                                }
                            } else if (device.kind === 'videoinput') {
                                if (this.localDevice.videoIn.filter(item => item.id === device.deviceId).length === 0) {
                                    this.localDevice.videoIn.push(obj)
                                }
                            }
                        })
                    })
                    .catch(this.handleError);
		        }).then(()=>{
					console.log(this.localDevice)
					console.log("audioIn", this.localDevice.audioIn)
					console.log("audioOut", this.localDevice.audioOut)
					console.log("videoIn", this.localDevice.videoIn)
				}).catch(this.handleError);
		},
        async handleFormSubmit() {
            const video = this.$refs.videoRef
            const stream = video.srcObject
            if (stream) {
                stream.getAudioTracks().forEach(e => {
                    stream.removeTrack(e)
                })
                stream.getVideoTracks().forEach(e => {
                    stream.removeTrack(e)
                })
            }
            let newStream = await this.switchDeviceMedia(this.formInline.videoId, this.formInline.audioInId)
            video.srcObject = newStream
            video.muted = true
        },
        async getLocalUserMedia(constraints){
            return await navigator.mediaDevices.getUserMedia(constraints)
        },
        async switchDeviceMedia(videoId, audioId){
            const constraints = {
                audio: { deviceId: audioId ? {exact: audioId} : undefined },
                video: {
                    deviceId: videoId ? {exact: videoId} : undefined,
                    width: { min: 320, ideal: this.formInline.width, max: 1920 },
                    height: { min: 240, ideal: this.formInline.height, max: 1080 },
                    frameRate: { ideal: this.formInline.frameRate, max: 24 },
                    facingMode: "user", // 移动端前置摄像头
                    // facingMode: { exact: "environment" } // 移动端后置摄像头
                }
            };
            if (window.stream) {
                window.stream.getTracks().forEach(track => {
                    track.stop();
                });
            }
            return await this.getLocalUserMedia(constraints).catch(this.handleError);
        },
    },
};
</script>

<style scoped lang="less">
    #videoElement {
		width: 500px;
		height: 400px;
	}
</style>
